<?php

namespace app\admin\controller\shops;

use app\common\controller\Backend;
use think\Db;
use app\common\model\Config;
use app\admin\model\Admin;
use app\common\model\OrderProof;

/**
 * 重复订单
 *
 * @icon fa fa-circle-o
 */
class Repetitive extends Backend
{

    /**
     * Shop模型对象
     * @var \app\admin\model\Shop
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Order;
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $channel = Db::name('channel')->select();
            $channellist = [];
            foreach ($channel as $key => $value) {
                $channellist[$value['id']] = $value['name'];
            }
            // 当前用户身份，如果是业务员，则只显示自己的活动
            $auth_group_access = Db::name('auth_group_access')->where('uid',$this->auth->id)->value('group_concat(group_id)');
            $explode = explode(',', $auth_group_access);
            $service_admin_id = [];
            $where2 = '1=1';
            if (in_array(5,$explode) && !in_array(1,$explode)) {
                $member = Db::name('admin')->where('leader',$this->auth->id)->value('group_concat(id)');
                $access_user = explode(',', $member);
                $access_user[] = $this->auth->id;
                $service_admin_id = $access_user;
                $salesman_str = implode(',', $service_admin_id);
                $where2 = 'order.service_admin_id in ('.$salesman_str.')';
            } elseif (in_array(3,$explode) && !in_array(1,$explode)) {// 业务员
                $service_admin_id = [$this->auth->id];
                $salesman_str = implode(',', $service_admin_id);
                $where2 = 'order.service_admin_id in ('.$salesman_str.')';
            }

            $list = $this->model->alias('order')
                    ->where($where)
                    ->where($where2)
                    ->field('*,count(wm_order_sn) as num,group_concat(is_yunzhan) as platform,group_concat(play_order_no) as play_order_nos,order.id as order_id,order.shop_no')
                    // ->join('chbc_shop shop','shop.shop_no=order.shop_no')
                    // ->where('order.order_status in (-9,-8,-7,-4,-3,-1,3,6)')
                    ->group('order.wm_order_sn')
                    ->having('count(order.wm_order_sn)>1')
                    ->order('place_time DESC')
                    ->paginate($limit);
            $datalist = [];
            foreach ($list as &$row) {
                $row['id'] = $row['order_id'];
                $platform = explode(',', $row['platform']);
                $play_order_nos = explode(',', $row['play_order_nos']);
                $row['platform']='';
                foreach ($platform as $key => $value) {
                    if ($key>0) $row['platform'] .= '</br>';
                    if ($value==0) {
                        $row['platform'] .= '渠道：吃喝不愁，订单号：'.$play_order_nos[$key];
                    } else {
                        $row['platform'] .= '渠道：'.$channellist[$value].'，订单号：'.$play_order_nos[$key];
                    }
                }
                // 处理状态
                $repetitive=Db::name('repetitive')->where(['wm_order_sn'=>$row['wm_order_sn']])->find();
                if ($repetitive) {
                    $row['order_status']=1;
                    $row['create_by'] = $repetitive['create_by'];
                } else {
                    $row['order_status']=0;
                    $row['create_by'] = '';
                }
                $data = $row;
                // 店铺id
                $data['shop_id'] = Db::name('shop')->where('shop_no',$row['shop_no'])->value('id');
                $datalist[] = $data;
            }

            $result = array("total" => $list->total(), "rows" => $datalist);

            return json($result);
        }
        // 当前用户身份，如果是业务员，业务员筛选那里只显示自己的名字
        $auth_group_access = Db::name('auth_group_access')->where('uid',$this->auth->id)->value('group_concat(group_id)');
        $explode = explode(',', $auth_group_access);
        $service_admin_id = [];
        if (in_array(5,$explode) && !in_array(1,$explode)) {
            $salesmanList = [];
            $member = Db::name('admin')->where('leader',$this->auth->id)->field('nickname')->select();
            foreach ($member as $key => $value) {
                $salesmanList[$value['nickname']] = $value['nickname'];
            }
        }elseif (in_array(1,$explode)) {
            $salesmanList = [];
            $salesman = $this->salesmanList();
            foreach ($salesman as $key => $value) {
                $salesmanList[$value['nickname']] = $value['nickname'];
            }
        } elseif (in_array(3,$explode) && !in_array(1,$explode)) {// 业务员
            $salesmanList = [];
            $salesmanList[$this->auth->nickname] = $this->auth->nickname;
        }
        $this->assignconfig(['salesmanList' => $salesmanList]);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $play_order = Db::name('play_order')->where('id',$ids)->find();
        $play_orders = Db::name('play_order')->where(['wm_order_sn'=>$play_order['wm_order_sn']])->select();
        $row = ['shop_name'=>$play_order['shop_name'],'wm_order_sn'=>$play_order['wm_order_sn']];
        $row['platform'] = '';
        foreach ($play_orders as $key => $value) {
            if ($key>0) $row['platform'] .= '</br>';
            $row['platform'] .= '渠道：'.Db::name('channel')->where('id',$value['is_yunzhan'])->value('name').'，订单号：'.$value['play_order_no'];
        }
        // 处理状态
        $repetitive=Db::name('repetitive')->where(['wm_order_sn'=>$play_order['wm_order_sn']])->find();
        if ($repetitive) {
            $row['order_status']='已处理';
            $row['create_by'] = $repetitive['create_by'];
        } else {
            $row['order_status']='未处理';
            $row['create_by'] = '';
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    public function agree($ids = null)
    {
        $play_order = Db::name('play_order')->where('id',$ids)->find();
        $play_orders = Db::name('play_order')->where(['wm_order_sn'=>$play_order['wm_order_sn']])->select();
        $count = count($play_orders);
        $count_1 = $count-1;
        $date = date('Y-m-d H:i:s');
        $data = [
            'wm_order_sn' => $play_order['wm_order_sn'],
            'status' => 1,
            'create_dt' => $date,
            'create_by' => $this->auth->nickname,
            'update_dt' => $date,
        ];
        Db::startTrans();
        try {
            Db::name('repetitive')->insert($data);
            $channel = Db::name('channel')->select();
            $channellist = [];
            foreach ($channel as $c) {
                $channellist[$c['id']] = $c['name'];
            }
            $remark = '';  // 异常备注
            $deduction_beans_arr = [];  // 扣除用户金额
            $financial_review_num_arr = [];   // 扣除商家账单金额
            $orderid=0;// 生效订单id，如果有吃喝不愁渠道使吃喝不愁生效其他失效，如果没有吃喝不愁渠道随机生效一个
            foreach ($play_orders as $key => $value) {
                if ($value['is_yunzhan']==0) {
                    $orderid=$value['id'];
                    $remark .= '吃喝不愁+';
                } else {
                    $remark .= $channellist[$value['is_yunzhan']].'+';
                }
                $deduction_beans_arr[$key] = round($value['actual_rebate_amt']*$count_1/$count,2);
                $financial_review_num_arr[$key] = round(($value['actual_rebate_amt']+$value['service_charge_amt'])*$count_1/$count,2);
            }
            $numbers = [1=>'一',2=>'二',3=>'三',4=>'四',5=>'五',6=>'六',7=>'七',8=>'八',9=>'九'];
            $remark = trim($remark,'+').'多平台返现，扣除'.$numbers[$count].'分之'.$numbers[$count_1];
            $orderController = new \app\admin\controller\order\Order();
            if (!$orderid) $orderid=$value['id'];
            Db::name('play_order')->where(['wm_order_sn'=>$play_order['wm_order_sn'],'id'=>['<>',$orderid]])->update(['is_effect'=>0]);
            // 处理提交订单异常
            foreach ($play_orders as $key => $row) {
                if ($row['order_status']!=3 && $row['order_status']!=6) {
                    $this->error('状态有误');
                }
                $orderProof = orderProof::where(['play_order_no'=>$row['play_order_no'],'handle_status'=>1])->order('id DESC')->find();
                if (!$orderProof) {
                    $this->error('提交有误');
                }
                $json = ['sj'=>['desc'=>2,'amount'=>$financial_review_num_arr[$key],'remark'=>''],'yh'=>['file'=>'','amount'=>$deduction_beans_arr[$key],'remark'=>''],'type'=>'提交财务'];
                $json = json_encode($json,JSON_UNESCAPED_UNICODE);
                // 产生售后事件
                $OrderAftersaleId = $orderController->OrderAftersale($this->auth->nickname,$this->auth->id,'业务员提交异常',$orderProof['play_order_no'],$row['play_no'],json_encode(['desc'=>'多平台返现','img'=>'','remark'=>$remark],JSON_UNESCAPED_UNICODE));
                $OrderAftersaleId = $orderController->OrderAftersale($this->auth->nickname,$this->auth->id,'客服审核拟取消或扣吃豆通过',$orderProof['play_order_no'],$row['play_no'],$json);
                $OrderAftersaleId = $orderController->OrderAftersale($this->auth->nickname,$this->auth->id,'财务已处理',$orderProof['play_order_no'],$row['play_no'],'');

                $orderProof->yc_remark = $remark;
                $orderProof->order_aftersale_id = $OrderAftersaleId;
                $orderProof->handle_merchant_id = $this->auth->id;
                $orderProof->handle_merchant_desc = json_encode(['desc'=>'多平台返现','img'=>'','remark'=>$remark],JSON_UNESCAPED_UNICODE);
                $orderProof->order_aftersale_id = $OrderAftersaleId;
                $orderProof->handle_admin_id = $this->auth->id;
                $orderProof->handle_admin_desc = $this->auth->nickname.'（）确认通过审核';
                $orderProof->yh_remark = '';
                $orderProof->sj_remark = '';
                $orderProof->financial_review = 2;
                $orderProof->financial_review_num = $financial_review_num_arr[$key];
                $orderProof->aftersale_evidence = '';
                $orderProof->deduction_beans = $deduction_beans_arr[$key];
                $orderProof->handle_status = 1;
                $orderProof->handle_time = time();
                $orderProof->save();
                // 订单log
                $orderController->orderLog($row['id'],$row['play_order_no'],'业务员帮商家提交异常',$this->auth->nickname,$this->auth->id);
                $orderController->orderLog($row['id'],$row['play_order_no'],'客服审核拟退还商家部分余额，数量:'.$financial_review_num_arr[$key],$this->auth->nickname,$this->auth->id);
                
                $orderController->orderLog($row['id'],$row['play_order_no'],'客服审核拟扣除用户部分吃豆，数量:'.$deduction_beans_arr[$key],$this->auth->nickname,$this->auth->id);
                $orderController->orderLog($row['id'],$row['play_order_no'],'财务已处理',$this->auth->nickname,$this->auth->id);
                // 订单状态
                $update['order_status'] = -9;
                $update['update_by'] = $this->auth->id;
                $update['actual_rebate_amt'] = $row['actual_rebate_amt']-$orderProof['financial_review_num'];
                // 减少渠道结算金额
                $aftersale = Db::name('play_order_aftersale')->order('id asc')->where(['play_order_no'=>$row['play_order_no']])->select();
                $deduction_beans=0;
                $financial_review_num=0;
                if ($aftersale) {
                    foreach ($aftersale as $key => &$value) {
                        if ($value['content']) {
                            $value['content'] = json_decode($value['content'],1);
                            if ($value['type']=='客服审核拟取消或扣吃豆通过') {
                                $deduction_beans+=$value['content']['yh']['amount'];
                                $financial_review_num+=$value['content']['sj']['amount'];
                            }
                            if ($value['type']=='修改渠道结算金额') {
                                $deduction_beans=$value['content']['value'];
                                $this->error('填写过“修改渠道结算金额”，不能再提交异常');
                            }
                            if ($value['type']=='修改商家结算金额') {
                                $financial_review_num=$value['content']['value'];
                                $this->error('填写过“修改商家结算金额”，不能再提交异常');
                            }
                        }
                    }
                }
                if ($deduction_beans==0) $deduction_beans += $deduction_beans_arr[$key];
                if ($financial_review_num==0) $financial_review_num += $financial_review_num_arr[$key];
                // 渠道结算金额
                // 商家应该支付的：商家需要付的减商家扣款的
                $yf = round($row['rebate_amt']-$financial_review_num,2);
                // 渠道应该获得的
                $qd = round($row['rebate_amt']-$row['service_charge_amt'],2);
                // 渠道实际获得的
                $update['actual_rebate_amt2'] = round($qd-$deduction_beans,2);
                // 重新计算后的平台服务费
                $update['service_charge_amt2'] = round($yf-$update['actual_rebate_amt2'],2);
                Db::name('play_order')->where('id',$row['id'])->update($update);
                // 更新吃喝不愁的异常
                if ($row['is_yunzhan']==0) {
                    \fast\Http::get(config('chbc_domain').'/index/yunzhan/notify?order_sn='.$row['play_order_no'].'&state=-7&source=2&origin=bdb&img=&desc=多平台返现&remark='.$remark);
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('处理失败');
        }
        $this->success();
    }


    public function add()
    {
        if ($this->request->isPost()) {
            $param = $this->request->post();
            $returndata = [];
            if (isset($param['date']) && isset($param['channel']) && $param['channel']) {
                if ($param['channel']==3) $param['channel']=0;
                $arr = explode(' - ', $param['date']);
                // 查询和渠道业务员对接的业务员组
                $ywy = [];
                if ($param['ywy']) {
                    $admin = Db::name('admin')->where('id',$param['ywy'])->find();
                    $leader2 = explode(',', trim($admin['leader2'],','));
                    if (!in_array($admin['id'], $leader2)) $leader2[] = $admin['id'];
                    $service_admin_ids = Db::name('admin')->where(['leader'=>['in',$leader2]])->value('group_concat(id)');
                    if ($service_admin_ids) $ywy = explode(',', $service_admin_ids);
                }
                $list = $this->model->alias('order')
                    ->field('*,count(wm_order_sn) as num,group_concat(is_yunzhan) as platform,group_concat(play_order_no) as play_order_nos,order.id as order_id,order.shop_no')
                    // ->join('chbc_shop shop','shop.shop_no=order.shop_no')
                    ->where('create_dt>="'.$arr[0].'" and create_dt<="'.$arr[1].'"')
                    ->group('order.wm_order_sn')
                    ->having('count(order.wm_order_sn)>1')
                    ->select();
                foreach ($list as $key => $value) {
                    $platform = explode(',', $value['platform']);
                    if (in_array($param['channel'], $platform)) {
                        $order = Db::name('play_order')->where(['wm_order_sn'=>$value['wm_order_sn'],'order_status'=>-9,'is_yunzhan'=>$param['channel']])->field('play_order_no,service_admin_id')->find();
                        if ($order) {
                            if (($ywy && in_array($order['service_admin_id'], $ywy) || !$ywy)) {
                                $aftersale = Db::name('play_order_aftersale')->where(['play_order_no'=>$order['play_order_no'],'type'=>'业务员提交异常'])->find();
                                if ($aftersale) {
                                    $content = json_decode($aftersale['content'],1);
                                    if (isset($content['remark']) && $content['remark']) {
                                        $returndata[] = $value['wm_order_sn'].' '.$content['remark'];
                                    }
                                }
                            }
                        }
                    }
                }
            }
            $this->success('消息已复制到剪贴板','',$returndata);
        }
        $channel = Db::name('channel')->field('id,name')->select();
        $qdywys = [];
        foreach ($channel as $key => $value) {
            $auth_group = Db::name('auth_group')->where(['pid'=>15,'name'=>$value['name']])->find();
            $auth_group_access = Db::name('auth_group_access')->where('group_id',$auth_group['id'])->select();
            $qdywy = [];
            if (count($auth_group_access)>0) {
                foreach ($auth_group_access as $k => $v) {
                    $admin = Db::name('admin')->where('id',$v['uid'])->field('id,nickname')->find();
                    if ($admin) $qdywy[] = ['id'=>$admin['id'],'nickname'=>$admin['nickname']];
                }
            }
            $qdywys[$value['name']] = $qdywy;
        }
        $this->view->assign("channel", $channel);
        $this->view->assign("qdywys", json_encode($qdywys,JSON_UNESCAPED_UNICODE));
        return $this->view->fetch();
    }

}
